package xyz.jcat.biz.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import xyz.jcat.biz.member.domain.dao.IMemberDao;
import xyz.jcat.biz.member.domain.po.MemberPo;
import xyz.jcat.biz.member.service.IMemberService;
import xyz.jcat.common.util.CodeUtils;
import xyz.jcat.common.util.RSAUtils;
import xyz.jcat.mybatis.ServiceImpl;

/**
 *
 * @author yueyue
 * auto on 2022-04-26 15:06:13
 */
@Service
public class MemberService extends ServiceImpl<IMemberDao, MemberPo> implements IMemberService {

    private static final String MEMBER_NICKNAME_PREFIX = "用户";
    private static final int BCRYPT_LOG_ROUNDS = 6;
    @Override
    public MemberPo getByPhone(String phone) {
        LambdaQueryWrapper<MemberPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MemberPo::getPhone, phone);
        return getOne(lambdaQueryWrapper);
    }

    @Override
    public MemberPo register(String phone, String password) {
        MemberPo member = new MemberPo();
        member.setPhone(phone);
        member.setPassword(CodeUtils.pwdEncrypt(RSAUtils.decrypt(password), BCRYPT_LOG_ROUNDS));
        member.setNickname(genDefaultNickname());
        insert(member);
        return member;
    }

    private String genDefaultNickname() {
        return MEMBER_NICKNAME_PREFIX+ RandomUtils.nextLong(100_000_000_000_000_000L, 1_000_000_000_000_000_000L);
    }
}
